<template>
  <n-card :bordered="false" class="proCard">
    <!--表单部分,可以动态创建表单-->
    <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
      <template #statusSlot="{ model, field }">
        <n-input v-model:value="model[field]" />
      </template>
    </BasicForm>

    <!--展示信息部分-->
    <BasicTable
      :columns="columns"
      :request="loadDataTable"
      :row-key="(row:ListData) => row.userId"
      ref="actionRef"
      :actionColumn="actionColumn"
      @update:checked-row-keys="onCheckedRow"
      :scroll-x="1090"
    >
      <template #tableTitle>
        <n-button type="primary" @click="exportEmp" style="margin-right: 10px;">导出数据</n-button>
        <n-upload ref="uploadComponent" action="#" :custom-request="customRequest"  accept=".xlsx" :show-file-list="false">
          <n-button type="primary" @click="reloadTable" >导入数据</n-button>
        </n-upload>

      </template>
      <template #deletedata>

      </template>
      <template #toolbar>
        <n-button type="primary" @click="showUserdrawer" style="margin-right: 10px;">
          新建
        </n-button>
        <n-button type="primary" :disabled="isRowKeysEmpty" @click="batchDelete" style="margin-right: 10px;"> 删除 </n-button>
        
        <n-button type="primary" @click="reloadTable" >刷新数据</n-button>
      </template>
    </BasicTable>

    <n-drawer v-model:show="showdrawer" :width="600">
      <n-drawer-content :title="titledrawer" closable>
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="100"
          class="py-4"
        >
          <n-grid :cols="24" :x-gap="24">
            <n-form-item-gi :span="12" label="姓名" path="username">
              <n-input placeholder="请输入姓名" v-model:value="formParams.username" :clearable="true" />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="身份证号" path="idCard">
              <n-input placeholder="请输入身份证号" v-model:value="formParams.idCard" :clearable="true"/>
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="性别" path="gender">
              <n-select
                v-model:value="formParams.gender"
                placeholder="请选择性别"
                :options="genderOptions"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="项目名称" path="project">
              <n-select
                v-model:value="formParams.project"
                placeholder="请选择项目"
                :options="selectProjectOptions"
                @update:value="handleSelectProject"
                :clearable="true"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="班组名称" path="group">
              <n-select
                v-model:value="formParams.group"
                placeholder="请选择班组"
                :options="selectGroupOptions"
                :disabled="isSelectGroupDisabled"
              />
            </n-form-item-gi>
            <n-form-item-gi :span="12" label="用户类型" path="role">
              <n-select
                v-model:value="formParams.role"
                placeholder="请选择"
                :options="roleOptions"
              />
            </n-form-item-gi>
          </n-grid>
          <n-card :bordered="false" class="proCard">
            <div>
              
              <a href="javascript:void(0);"><input type="file" class="upfile" @change="convertToBase64" accept=".jpg,.jpeg,.png"><span>上传照片</span></a>
              <div v-if="imageBase64">
                <img :src="imageBase64" alt="Uploaded Image" :width="160" :height="100" style="margin-top: 20px;">
              </div>
            </div>

          </n-card>
        </n-form>
        <template #footer>
          <n-button type="primary" @click="saveuserinfo"> 提交 </n-button>
        </template>
      </n-drawer-content>
    </n-drawer>
  </n-card>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref, toRefs, unref, watch, computed } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import {
    getTableList,
    getGroupOptions,
    getProjcetOptions,
    batchDelUser,
    createUser,
    updateUser,
    getEditInit,
    uploadExcel,
    getEmpExcel,
  } from '@/api/employee/employee';
  import { columns, ListData } from './columns';
  import { type FormRules } from 'naive-ui';

  const selectProjectOptions = ref([]);
  const selectGroupOptions = ref([]);
  const isSelectGroupDisabled = ref(true);
  // 获取第一个下拉框的选项数据
  onMounted(async () => {
    try {
      const options = await getProjcetOptions();
      selectProjectOptions.value = options;
    } catch (error) {
      console.error('Failed to fetch project options:', error);
    }
  });
  // 获取第二个下拉框的选项数据
  async function fetchAndSetGroupOptions(params) {
    try {
      const options = await getGroupOptions(params);

      selectGroupOptions.value = options;
    } catch (error) {
      console.error('Failed to fetch group options:', error);
    }
  }

  const schemas: FormSchema[] = [
    {
      field: 'selectProject',
      component: 'NSelect',
      label: '选择项目',
      componentProps: {
        clearable: false,
        placeholder: '请选择项目',
        options: selectProjectOptions,
        onUpdateValue: (e: any) => {
          console.log('selectProjectOptions', e);
          if (e === null) {
            // 如果第一个下拉框没有选项，则禁用第二个下拉框
            isSelectGroupDisabled.value = true;
          } else {
            // 否则启用第二个下拉框，并根据需要更新选项
            isSelectGroupDisabled.value = false;
            fetchAndSetGroupOptions({ selectProject: e });
          }
        },
      },
    },
    {
      field: 'selectGroup',
      component: 'NSelect',
      label: '选择班组',
      componentProps: {
        clearable: true,
        disabled: isSelectGroupDisabled,
        placeholder: '请选择班组',
        options: selectGroupOptions,
        onUpdateValue: (e: any) => {
          // console.log('selectGroupOptions', e);
        },
      },
    },
    {
      field: 'searchValue',
      component: 'NInput',
      label: '快速查询',
      componentProps: {
        placeholder: '请输入姓名',
        onInput: (e: any) => {
          // console.log('searchValue', e);
        },
      },
      rules: [{ required: false, message: '请输入姓名', trigger: ['blur'] }],
    },
  ];
  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    schemas,
    showAdvancedButton: false,
  });

  const formRef: any = ref(null);
  const actionRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);


  const showdrawer = ref(false);
  const titledrawer = ref('');

  const validateIdCard = (rule, value, callback) => {
    const idCardPattern = /^\d{17}(\d|X|x)$/;
    if (!value) {
      // callback(new Error('请输入身份证号'));
    } else if (!idCardPattern.test(value)) {
      callback(new Error('身份证号格式不正确'));
    } else {
      callback();
    }
  };

  const rules: FormRules = {
    username: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入用户名',
    },
    idCard: [
      { required: true, trigger: ['blur', 'input'], message: '请输入身份证号' },
      { validator: validateIdCard, trigger: ['blur', 'input'] },
    ],
    gender: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择性别',
    },
    project: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择项目',
    },
    group: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择班组',
    },
    role: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请选择角色',
    },
  };
  const imageBase64 = ref(null);

  const formParams = reactive({
    username: '',
    idCard: '',
    project: '',
    group: '',
    role: '',
    employee_id: '',
    photo: '',
    gender: '',
  });

  function showUserdrawer() {
    showdrawer.value = true;
    titledrawer.value = '新建用户';
    formParams.username = '';
    formParams.idCard = '';
    formParams.project = '';
    formParams.group = '';
    formParams.role = '';
    formParams.photo = '';
    formParams.gender = '';
    imageBase64.value = '';

  }

  const roleOptions = reactive([
        {
          label: '管理员',
          value: '1'
        },
        {
          label: '普通工人',
          value: '0'
        }
      ]);
    
  const genderOptions = reactive([
        {
          label: '男',
          value: '男'
        },
        {
          label: '女',
          value: '女'
        }
    ]);
  function handleSelectProject(value) {
    if (value === null) {
      // 如果第一个下拉框没有选项，则禁用第二个下拉框
      isSelectGroupDisabled.value = true;
      selectGroupOptions.value = [];
      formParams.group = '';
    } else {
      // 否则启用第二个下拉框，并根据需要更新选项
      console.log('projectid:', formParams.project);
      isSelectGroupDisabled.value = false;
      selectGroupOptions.value = [];
      formParams.group = '';
      fetchAndSetGroupOptions({ selectProject: value });
    }
  }
 
 function convertToBase64(event) {
   const file = event.target.files[0];
   if (file) {
     const reader = new FileReader();
     reader.onload = (e) => {
       imageBase64.value = e.target.result;
       formParams.photo = e.target.result;
     };
     reader.readAsDataURL(file);
   }
  }


  interface FileInfo {
    id: string;
    name: string;
    batchId?: string | null;
    percentage?: number | null;
    status: 'pending' | 'uploading' | 'finished' | 'removed' | 'error';
    url?: string | null;
    file?: File | null;
    thumbnailUrl?: string | null;
    type?: string | null;
    fullPath?: string | null;
  }
 
  interface UploadCustomRequestOptions {
    file: FileInfo;
    action?: string;
    data?: Record<string, string> | (({ file }: { file: FileInfo }) => Record<string, string>);
    withCredentials?: boolean;
    headers?: Record<string, string> | (({ file }: { file: FileInfo }) => Record<string, string>);
    onProgress: (e: { percent: number }) => void;
    onFinish: () => void;
    onError: () => void;
  }

  const uploadComponent = ref(null);
  //上传
  const customRequest = async ({ file }: UploadCustomRequestOptions) => {
    await uploadExcel(file).then(() => {
      window['$message'].success('导入成功');
      if (uploadComponent.value) {
        uploadComponent.value.clear();
      }
      reloadTable();
    });

  };

  function saveuserinfo() {
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        if (formParams.photo == '') {
          window['$dialog'].info({
            title: '提示',
            content: "请上传员工照片！",
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {return;},
            onNegativeClick: () => {},
          });
        }
        if (titledrawer.value == "编辑用户") {
          // 编辑用户
          const params = formParams;
          console.log('修改', formParams);
          await updateUser(params);
          window['$message'].success('编辑成功');
        } else {
          // 创建用户
          const params = formParams;
          await createUser(params);
          window['$message'].success('新建成功');
        }
        setTimeout(() => {
          showdrawer.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请输入完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  // 数据表格部分的actionColumn
  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            // auth: ['basic_list'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            // auth: ['basic_list'],
          },
        ],
        dropDownActions: [
          {
            label: '启用',
            key: 'enabled',
            // 根据业务控制是否显示: 非enable状态的不显示启用按钮
            ifShow: () => {
              return true;
            },
          },
          {
            label: '禁用',
            key: 'disabled',
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          window['$message'].info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  // 加载数据表
  const loadDataTable = async (res) => {
    const data = await getTableList({ ...getFieldsValue(), ...res });
    console.log('loadDataTableRes:', data);
    return data;
  };

  //cdx：其他地方使用rowKeys，需要将其定义为一个响应式变量
  const rowKeys = ref([]);
  function onCheckedRow(rKeys) {
    console.log('选中的行数据', rKeys);
    rowKeys.value = rKeys;
    console.log('rowKeys.value', rowKeys.value.length);
  }

  //cdx：控制删除按钮是否可以点击，计算选中数据list的length是否为0。奇怪的是，直接在组件绑定“rowKeys.value.length === 0”会报错，转换为计算属性即可
  const isRowKeysEmpty = computed(() => {
    return rowKeys.value.length === 0;
  });

  function reloadTable() {
    actionRef.value.reload();
  }

  async function getempexcel() {
    const data = await getEmpExcel({...getFieldsValue()});
    return data;
  }

  function exportEmp() {
    getempexcel().then((response) => {
      const url = window.URL.createObjectURL(response.data)
      const fileName = '人员信息（导出）.xlsx';
      let a = document.createElement('a');
      a.download = fileName;
      a.href = url;
      document.body.append(a);
      a.click();
      URL.revokeObjectURL(a.href);
      a.remove();
    });
  }
  function confirmForm(e) {
    console.log('新建信息：', formParams);
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('新建信息：', formParams);
        window['$message'].success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }
  const editInitParams = ref({});
  // cdx：表格里面的编辑按钮对应的函数
  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    editInitParams.value = await getEditInit({ employeeID: record.userId });
    console.log('init parmas:', editInitParams.value);
    showdrawer.value = true;
    titledrawer.value = '编辑用户';
    formParams.username = editInitParams.value.name;
    formParams.idCard = editInitParams.value.idCard;
    formParams.project = editInitParams.value.project_name;
    formParams.group = editInitParams.value.group_name;
    formParams.role = editInitParams.value.role;
    formParams.employee_id = record.userId;
    formParams.photo = record.avatar;
    formParams.gender = record.gender;
    imageBase64.value = record.avatar;
  }

  async function handleDelete(record: Recordable) {
    console.log('单挑删除的数据', [record.userId]);
    try {
      const res = await batchDelUser({ delUserList: [record.userId] });
      window['$message'].info('点击了删除');
      reloadTable();
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('DelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }
  // cdx：表格上方的批量删除按钮对应的函数
  async function batchDelete() {
    console.log('批量删除的数据2:', rowKeys.value);
    try {
      const res = await batchDelUser({ delUserList: rowKeys.value });
      window['$message'].info('点击了删除');
      reloadTable();
      // router.push({ path: '/redirect' + unref(route).fullPath });
      console.log('batchDelRes:', res);
    } catch (error) {
      console.error('批量删除失败：', error);
    }
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    reloadTable();
  }
</script>

<style lang="less" scoped>
    .upfile{cursor:pointer;direction:rtl;height:30px;opacity:0;width:90px;filter:alpha(opacity=0); position:absolute;top:0;left:0}
    a{
        position:relative;cursor:pointer;display:block;height:30px;cursor:pointer;margin-top:7px;overflow:hidden;width:90px;background:#fefefe;border:1px solid #dcdcdc;line-height:30px;text-align:center;font-size:14px;color:#333;text-decoration:none;border-radius:5px;
        background:-moz-linear-gradient(center top,#ffffff,#f6f6f6 50%,#f6f6f6 50%,#ededed);
        background:-o-linear-gradient(top left,#ffffff,#f6f6f6 50%,#f6f6f6 50%,#ededed);
        background:-webkit-gradient(linear,0% 0,0% 100%,from( #ffffff),to( #f6f6f6),color-stop(.5,#f6f6f6),color-stop(.5,#ededed));
        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff',endColorstr='#ededed');
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#ffffff', endColorstr='#ededed')";
    }
    a:hover{
        background:-moz-linear-gradient(center top,#f9f9f9,#efefef 50%,#efefef 50%,#e4e4e4);
        background:-o-linear-gradient(top left,#f9f9f9,#efefef 50%,#efefef 50%,#e4e4e4);
        background:-webkit-gradient(linear,0% 0,0% 100%,from( #f9f9f9),to( #efefef),color-stop(.5,#efefef),color-stop(.5,#e4e4e4));
        filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f9f9f9',endColorstr='#e4e4e4');
        -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#f9f9f9', endColorstr='#e4e4e4')";
    }
</style>
